package com.fjrz.bbxwj.main.video.base

import android.Manifest
import android.os.Bundle
import android.view.View
import com.blankj.utilcode.util.LogUtils
import com.fjrz.bbxwj.R
import com.fjrz.bbxwj.app.RZApplication
import com.fjrz.bbxwj.entity.User
import com.fjrz.bbxwj.entity.VideoList
import com.fjrz.bbxwj.main.access.AccessActivity
import com.fjrz.bbxwj.main.host.side.MainUserInfoActivity
import com.fjrz.bbxwj.util.LocationUtils
import com.module.lemlin.view.LoginAuthPopup
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.tbruyelle.rxpermissions3.RxPermissions
import io.reactivex.disposables.Disposable

class VideoCityFragment : BaseVideoFragment() {

    companion object {
        private const val EXTRA_NAME_CITY = "EXTRA_NAME_CITY"
        fun newInstance(city: String): VideoCityFragment {
            val bundle: Bundle = Bundle().apply {
                putString(EXTRA_NAME_CITY, city)
            }
            return VideoCityFragment().apply { arguments = bundle }
        }
    }

    private val mCity: String
        get() = arguments?.getString(EXTRA_NAME_CITY) ?: ""

    override fun initData() {
        val rxPermission = RxPermissions(this)
        rxPermission.request(
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION
        ).subscribe { permission ->
            if (!permission) {
                toast(message = "请到设置中开启位置权限")
            } else LocationUtils.location(
                requireContext(), object : LocationUtils.OnSubAdminAreaListener {
                    override fun onSubAdminArea(adminArea: String?, subAdminArea: String?) {
                        viewModel.videoSameCityList(subAdminArea ?: mCity)
                    }
                })
        }
    }

    override fun setOnItemChildClickListener(videoList: VideoList, view: View, position: Int) {
        if (RZApplication.token().isNullOrEmpty()) {
            AccessActivity.open(activity = requireActivity())
            return
        }
        super.setOnItemChildClickListener(videoList, view, position)
        if (view.id == R.id.ivControlsHeads) MainUserInfoActivity.open(
            activity = requireActivity(),
            user = if (RZApplication.userInfoMe()?.id == videoList.user.id)
                videoList.user.apply { who = User.Who.USER_ME }
            else videoList.user.apply { who = User.Who.USER_HE }
        )
    }

    override fun setOnRefreshListener(refreshLayout: RefreshLayout) {
        viewModel.videoSameCityList(mCity)
    }

    override fun setOnLoadMoreListener(refreshLayout: RefreshLayout) {
        viewModel.videoSameCityList(mCity, isLoadMore = true)
    }


    override fun onEventMainThread(any: Any) {
        super.onEventMainThread(any)
        if (any !is LoginAuthPopup.Action)
            return
        if (any == LoginAuthPopup.Action.ACTION_LOGIN_SUCCESS) {
            initData()
        }
    }
}